package com.example.logindemo.service.impl;

import com.example.logindemo.entity.Role;
import com.example.logindemo.entity.User;
import com.example.logindemo.event.UserRegistrationEvent;
import com.example.logindemo.repository.RoleRepository;
import com.example.logindemo.repository.UserRepository;
import com.example.logindemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private RoleRepository roleRepository;
    
    @Autowired
    private ApplicationEventPublisher eventPublisher;
    
    // 头像存储路径
    private final Path avatarUploadLocation;
    
    public UserServiceImpl() {
        // 创建头像存储路径（使用绝对路径）
        this.avatarUploadLocation = Paths.get("uploads/avatars").toAbsolutePath().normalize();
        
        // 创建头像存储目录
        try {
            if (!Files.exists(this.avatarUploadLocation)) {
                Files.createDirectories(this.avatarUploadLocation);
            }
        } catch (IOException ex) {
            throw new RuntimeException("无法创建头像上传目录", ex);
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    @Cacheable(value = "users", key = "#username")
    public User getUserByUsername(String username) {
        return userRepository.findByUsername(username).orElse(null);
    }
    
    @Override
    public String updateAvatar(String username, MultipartFile file) throws IOException {
        // 由于数据库结构中没有avatar字段，此方法暂时不可用
        throw new UnsupportedOperationException("头像功能暂时不可用");
    }
    
    @Override
    @Transactional
    @CacheEvict(value = "users", key = "#username")
    public User updateUserInfo(String username, User userInfo) {
        User user = userRepository.findByUsername(username).orElse(null);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 更新用户信息
        if (userInfo.getEmail() != null) {
            user.setEmail(userInfo.getEmail());
        }
        if (userInfo.getPhoneNumber() != null) {
            user.setPhoneNumber(userInfo.getPhoneNumber());
        }
        
        user.setUpdataTime(new Date());
        return userRepository.save(user);
    }
    
    @Override
    @Transactional
    @CacheEvict(value = "users", allEntries = true)
    public User createUser(User user) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        user.setRegistTime(new Date());
        user.setUpdataTime(new Date());
        
        // 获取或创建USER角色
        Role userRole = roleRepository.findByName("USER")
            .orElseGet(() -> {
                Role newRole = new Role("USER", "普通用户角色");
                return roleRepository.save(newRole);
            });
        
        // 为用户分配USER角色
        user.addRole(userRole);
        
        User savedUser = userRepository.save(user);
        
        // 发布用户注册事件，通知监听器为新用户创建测试数据
        eventPublisher.publishEvent(new UserRegistrationEvent(this, savedUser));
        
        return savedUser;
    }
}